function(TEMPORARY_DIRECTORY)
  if(NOT DEFINED TEMPORARY_DIRECTORY)
    if(DEFINED ENV{TMPDIR})
      set(TEMPORARY_DIRECTORY $ENV{TMPDIR})
    elseif(DEFINED ENV{TEMP})
      set(TEMPORARY_DIRECTORY $ENV{TEMP})
    elseif(DEFINED ENV{TMP})
      set(TEMPORARY_DIRECTORY $ENV{TMP})
    endif()
  endif()
  if(NOT DEFINED TEMPORARY_DIRECTORY)
    find_program(MKTEMP NAMES mktemp)
    if(EXISTS "${MKTEMP}")
      execute_process(COMMAND ${MKTEMP} -d OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE dir RESULT_VARIABLE result)
      if(result EQUAL 0)
        get_filename_component(TEMPORARY_DIRECTORY "${dir}" DIRECTORY)
      endif()
    endif()
  endif()
  if(DEFINED TEMPORARY_DIRECTORY)
    set(TEMPORARY_DIRECTORY ${TEMPORARY_DIRECTORY} CACHE PATH "Path to system temporary directory.")
  endif()
endfunction()
if(NOT DEFINED TEMPORARY_DIRECTORY)
  TEMPORARY_DIRECTORY()
endif()
